package com.king.service;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;

/**
 * 业务处理逻辑
 * 读取客户端数据，进行业务逻辑处理，最终返回结果给客户端
 *
 * @author king
 * @date 2020/12/21 18:23
 */
@ChannelHandler.Sharable
public class ServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 读取客户端发送的数据
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ByteBuf) {
            // ByteBuf 的 toString() 方法把二进制数据转换成字符串，默认编码 UTF-8
            System.out.println(((ByteBuf) msg).toString(Charset.defaultCharset()));
        }
        ctx.channel().writeAndFlush("msg has recived!");
    }
}
